package com.duowei.dw_pos.tools;

import android.Manifest;
import android.annotation.SuppressLint;
import android.support.annotation.Size;
import android.support.v7.app.AppCompatActivity;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.functions.Consumer;

/**
 * dr
 * 2019年3月12日18:10:24
 */
public class PermissionsUtil {
    private static final String TAG =  PermissionsUtil.class.getSimpleName();

    public static final int CODE_WRITE_EXTERNAL_STORAGE = 1;
    public static final int CODE_READ_PHONE_STATE = 2;
    public static final int CODE_CAMERA = 3;
//    public static final int CODE_RECORD_AUDIO = 4;
//    public static final int CODE_READ_SMS = 4;
    public static final int CODE_MULTI_PERMISSION = 100;

    public static final String PERMISSION_WRITE_EXTERNAL_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    public static final String PERMISSION_READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE;
    public static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
//    public static final String PERMISSION_RECORD_AUDIO = Manifest.permission.RECORD_AUDIO;
//    public static final String PERMISSION_READ_SMS = Manifest.permission.READ_SMS;

    /**
     * 动态申请所有权限数组（相机权限使用时再请求）
     */
    public static final String[] allPermissions = {
//            PERMISSION_RECORD_AUDIO,
            PERMISSION_READ_PHONE_STATE,
            PERMISSION_CAMERA,
            PERMISSION_WRITE_EXTERNAL_STORAGE,
//            PERMISSION_READ_SMS
    };

    /**
     * 权限申请（支持多个）
     * @param activity      权限申请活动界面
     * @param permissions   所需申请的权限
     */
    @SuppressLint("CheckResult")
    public static void requestPermissions(final AppCompatActivity activity, @Size(min = 1) String... permissions){
        RxPermissions rxPermissions = new RxPermissions(activity);
        if (permissions.length > 1){
            rxPermissions.requestEach(permissions).subscribe(new Consumer<Permission>() {
                @Override
                public void accept(Permission permission) throws Exception {
                    if (permission.granted){
                        // 用户已经授权该权限
                    }else if(permission.shouldShowRequestPermissionRationale){
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                    }else{
                        // 用户拒绝了该权限，并且选中『不再询问』
                        ToastUtil.showShortToast(activity, "用户拒绝了该权限，并且选中『不再询问』，请在设置中授权");
                    }
                }
            });
        }else {
            rxPermissions.request(permissions).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) {
                    if (aBoolean) {
                        // 用户已经授权该权限
                    } else {
                        // 用户拒绝了该权限
                    }
                }
            });
        }
    }
}
